package org.springframework.learn.beans.note.resource;

import org.springframework.context.EnvironmentAware;
import org.springframework.context.annotation.AnnotationConfigApplicationContext;
import org.springframework.context.annotation.ClassPathBeanDefinitionScanner;
import org.springframework.context.annotation.ClassPathScanningCandidateComponentProvider;
import org.springframework.core.env.Environment;
import org.springframework.core.env.StandardEnvironment;
import org.springframework.core.io.Resource;
import org.springframework.core.io.support.PathMatchingResourcePatternResolver;
import org.springframework.core.io.support.ResourcePatternResolver;
import org.springframework.util.ClassUtils;
import org.springframework.util.ResourceUtils;

import java.io.File;
import java.io.IOException;

/**
 * 参考源码{@link ClassPathScanningCandidateComponentProvider#scanCandidateComponents(String)}
 *
 * @author chenjiquan
 * @date 2023-12-08
 */
public class ResourceNote implements EnvironmentAware {

	/**
	 * 目录和子目录
	 */
	static final String DEFAULT_RESOURCE_PATTERN = "**/*.class";
	private static String resourcePattern = DEFAULT_RESOURCE_PATTERN;

	Environment environment;

	public static void main(String[] args) throws IOException {

		AnnotationConfigApplicationContext context = new AnnotationConfigApplicationContext(ResourceNote.class);

		Resource resource = context.getResource("classpath:dev/dev.yaml");
		System.out.println(resource.getFile());


		Resource[] resources = context.getResources("classpath:com/learn/mapper/*.class");
		for (Resource r : resources) {
			System.out.println(r.getFilename());
		}


		File file = ResourceUtils.getFile(ResourceUtils.CLASSPATH_URL_PREFIX + "dev/dev.yaml");
		System.out.println(file);

	}


	void test() throws IOException {
		ResourcePatternResolver resolver = new PathMatchingResourcePatternResolver();
		String basePackage = "";
		// 将包路径转换为资源路径
		String packageSearchPath = ResourcePatternResolver.CLASSPATH_ALL_URL_PREFIX +
				resolveBasePackage(basePackage) + '/' + resourcePattern;
		// 扫描指定资源路径下的所有.class文件
		Resource[] resources = resolver.getResources(packageSearchPath);
	}

	protected String resolveBasePackage(String basePackage) {
		return ClassUtils.convertClassNameToResourcePath(environment.resolveRequiredPlaceholders(basePackage));
	}


	@Override
	public void setEnvironment(Environment environment) {
		this.environment = environment;
	}
}
